package com.ethink.framework.common.web.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.ethink.framework.common.constant.CommonConstant;
import org.apache.commons.lang3.StringUtils;

/**
 * 请求上下文 holder
 *
 * @author yunduo
 * @Date 2020-06-01
 */
public class SPRequestContextHolder {

    /**
     * 支持父子线程之间的数据传递
     */
    private static final ThreadLocal<RequestContext> CONTEXT = new TransmittableThreadLocal<>();

    /**
     * 获取请求上下文
     *
     * @return
     */
    public static RequestContext getRequestContext() {
        return CONTEXT.get();
    }

    /**
     * 设置请求上下文
     *
     * @param requestContext
     */
    public static void setRequestContext(RequestContext requestContext) {
        CONTEXT.set(requestContext);
    }


    /**
     * 清除缓存
     */
    public static void clear() {
        CONTEXT.remove();
    }

    /**
     * 添加业务参数
     *
     * @param name
     * @param value
     */
    public static void setBizParam(String name, Object value) {
        RequestContext requestContext = getRequestContext();
        if (requestContext == null) {
            requestContext = new RequestContext();
            CONTEXT.set(requestContext);
        }
        requestContext.getBizParamMap().put(name, value == null ? null : String.valueOf(value));
    }

    /**
     * 获取业务参数
     *
     * @param name
     * @return
     */
    public static String getBizParam(String name) {
        RequestContext requestContext = CONTEXT.get();
        return requestContext == null ? null : requestContext.getBizParamMap().get(name);
    }

    /**
     * 设置商户id
     *
     * @param merchantId
     */
    public static void setMerchantId(Long merchantId) {
        setBizParam(CommonConstant.RequestHeader.MERCHANT_ID, merchantId);
    }

    /**
     * 获取商户id
     *
     * @return
     */
    public static Long getMerchantId() {
        String value = getBizParam(CommonConstant.RequestHeader.MERCHANT_ID);
        return StringUtils.isBlank(value) ? null : Long.valueOf(value);
    }

    public static String getToken() {
        return getBizParam(CommonConstant.RequestHeader.SYSTEM_TOKEN);
    }

    /**
     * 获取当前用户ID
     *
     * @return
     */
    public static Long getCurrentUser() {
        return 1L;
    }

    /**
     * 获取当前用户code
     *
     * @return
     */
    public static String getCurrentSystemUserLoginName() {
        return getBizParam(CommonConstant.RequestHeader.SYSTEM_LOGIN_NAME);
    }

    /**
     * 获取当前用户name
     *
     * @return
     */
    public static String getCurrentSystemUserRealName() {
        return getBizParam(CommonConstant.RequestHeader.SYSTEM_REAL_NAME);
    }
}
